import { defineStore } from 'pinia';
import store from '@/store';
import { Md5 } from 'ts-md5';
import { getUserAuthorize, login } from '@/api/user';
import type { LoginReq, LoginRes } from '@/api/user';
import type { UserAuthorizeRes } from '@/api/user';
import { licenceVerification } from '@/api/licence';
import { setToken, setUserInfo } from '@/utils/cookies';

let Message;
nextTick(() => {
	Message = window['$message'];
});
interface UserState {
	token: string;
	userInfo: LoginRes | null;
	hasLicence: boolean;
	allMenuRoles: UserAuthorizeRes[];
	allRoles: string[];
	menuRole: string[];
	settingRole: string[];
}

export const useUserStore = defineStore('app-user', {
	state: (): UserState => ({
		token: '',
		userInfo: null,
		hasLicence: false,
		allMenuRoles: [],
		allRoles: [],
		menuRole: [],
		settingRole: [],
	}),
	actions: {
		login(form: LoginReq) {
			return new Promise(async (resolve, reject) => {
				try {
					const params = {
						loginName: form.loginName,
						password: Md5.hashStr(form.password),
						saveUserName: true,
					};
					const { results } = await login(params);
					this.userInfo = results;
					setToken(results.token);
					const userInfo = {
						id: results.id,
						loginName: results.loginName,
						userName: results.userName,
					};
					setUserInfo(JSON.stringify(userInfo));
					// this.licenceVerification();
					resolve(results);
					return results;
				} catch (error) {
					reject();
					// Message.error('用户名或密码错误');
				}
			});
		},
		async licenceVerification() {
			try {
				const { results } = await licenceVerification();
				const days = Number(results);
				if (days > 0) {
					this.hasLicence = true;
				} else if (days <= 0) {
					this.hasLicence = false;
					Message.warning('licencs已过期，请重新导入licence');
				}
			} catch {
				// Message.warning('获取licencs错误或licencs已过期，请重新导入licence');
				this.hasLicence = false;
			}
		},
		getUserAuthorize() {
			interface PromiseResolve {
				allRoles: string[];
			}
			return new Promise<PromiseResolve>(async (resolve, reject) => {
				try {
					const { results } = await getUserAuthorize();
					this.allMenuRoles = JSON.parse(JSON.stringify(results));
					const menuRole: string[] = [];
					const settingRole: string[] = [];
					results.map(item => {
						if (item.authType === 1) {
							menuRole.push(item.authName);
						} else {
							settingRole.push(item.authName);
						}
					});
					const allRoles = [...menuRole, ...settingRole];
					this.menuRole = menuRole;
					this.settingRole = settingRole;
					this.allRoles = allRoles;
					resolve({ allRoles });
				} catch (error) {
					reject();
				}
			});
		},
	},
});

// Need to be used outside the setup
export function useUserStoreWithOut() {
	return useUserStore(store);
}
